<template>
  <div style="width: 650px">
    <el-row>
      <el-col :span="24">
        <el-card class="task-card">
          <template #header>
            <div class="button-group">
              <span style="font-size: large; font-weight: 600">红线监测任务成果管理</span>
              <el-button type="success" @click="openCreateDialog">任务创建</el-button>
            </div>
          </template>

          <!-- 查询表单 -->
          <el-form class="query-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="任务名称">
                  <el-input
                    v-model="filters.resultName"
                    placeholder="请输入任务名称"
                    clearable
                    style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检测时间">
                  <el-select
                    v-model="filters.detectionTime"
                    placeholder="选择检测时间"
                    clearable
                    style="width: 100%"
                  >
                    <el-option label="2024第一季度" value="2024第一季度"></el-option>
                    <el-option label="2024第二季度" value="2024第二季度"></el-option>
                    <el-option label="2024第三季度" value="2024第三季度"></el-option>
                    <el-option label="2024第四季度" value="2024第四季度"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="任务类型">
                  <el-select
                    v-model="filters.taskType"
                    placeholder="选择任务类型"
                    clearable
                    style="width: 100%"
                  >
                    <el-option label="变化检测" value="变化检测"></el-option>
                    <el-option label="地物分类" value="地物分类"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任务来源">
                  <el-select
                    v-model="filters.taskSource"
                    placeholder="选择任务来源"
                    clearable
                    style="width: 100%"
                  >
                    <el-option label="系统自动生成" value="系统自动生成"></el-option>
                    <el-option label="中心下发" value="中心下发"></el-option>
                    <el-option label="委托生产" value="委托生产"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item>
              <div class="query-buttons" style="display: flex; justify-content: flex-end">
                <el-button @click="resetFilters">重置</el-button>
                <el-button type="primary" @click="applyFilters">筛选</el-button>
              </div>
            </el-form-item>
          </el-form>

          <!-- 数据表格 -->
          <el-table
            :data="tasks"
            style="width: 100%; margin-top: 20px"
            height="880"
            v-loading="loading"
          >
            <el-table-column
              label="序号"
              :align="'center'"
              type="index"
              width="60"
            ></el-table-column>
            <el-table-column
              label="任务名称"
              width="150"
              prop="resultName"
            ></el-table-column>
            <el-table-column
              label="任务来源"
              width="110"
              prop="taskSource"
            ></el-table-column>
            <el-table-column label="任务类型" width="110" prop="taskType">
              <template #default="scope">
                <el-tag type="success" effect="plain">{{
                  scope.row.taskType
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="监测时间"
              width="90"
              prop="detectionTime"
            ></el-table-column>
            <el-table-column label="操作" width="180"  :align="'center'">
              <template #default="{ row }">
                <el-button-group>
                  <el-button size="small" type="primary" @click="handleDownload(row)">下载</el-button>
                  <el-button size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
                  <el-button size="small" type="primary" @click="handleDelete(row)">删除</el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            :total="totalTasks"
            :page-size="pageSize"
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            @current-change="handlePageChange"
            style="margin-top: 20px; text-align: center"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 任务操作对话框 -->
    <task-result-dialog 
      :visible="dialogVisible" 
      :is-editing="isEditing"
      :task="currentTask"
      @close="dialogVisible = false"
      @confirm="confirmDialog"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import TaskResultDialog from './TaskResultList.vue';

// 任务列表数据
const tasks = ref<any[]>([]);

// 加载状态
const loading = ref(false);

// 对话框控制
const dialogVisible = ref(false);
const isEditing = ref(false);

// 当前任务（创建/编辑）
const currentTask = reactive({
  id: '',
  resultName: "",
  taskType: "变化检测",
  taskSource: "",
  detectionTime: "",
});

// 筛选条件
const filters = reactive({
  detectionTime: "",
  resultName: "",
  taskType: "变化检测",
  taskSource: "",
});

// 分页参数
const totalTasks = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 获取任务列表的方法
const fetchTaskResults = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const queryParams: any = {
      page: currentPage.value,
      limit: pageSize.value,
    };

    // 添加各种查询条件
    if (filters.resultName) {
      queryParams.resultName = filters.resultName;
    }

    if (filters.detectionTime) {
      queryParams.detectionTime = filters.detectionTime;
    }

    if (filters.taskType) {
      queryParams.taskType = filters.taskType;
    }

    if (filters.taskSource) {
      queryParams.taskSource = filters.taskSource;
    }

    // 发起查询请求
    const response = await axios.get("/algorithmApi/task-result/query", {
      params: queryParams,
    });

    // 更新任务列表和总数
    tasks.value = response.data.list;
    totalTasks.value = response.data.total;
  } catch (error) {
    console.error("获取任务列表失败:", error);
    ElMessage.error("获取任务列表失败");
  } finally {
    loading.value = false;
  }
};

// 打开创建任务弹窗
const openCreateDialog = () => {
  isEditing.value = false;
  // 重置表单
  currentTask.id = '';
  currentTask.resultName = "";
  currentTask.taskType = "变化检测";
  currentTask.taskSource = "";
  currentTask.detectionTime = "";
  
  dialogVisible.value = true;
};

// 打开编辑任务弹窗
const openEditDialog = (row: any) => {
  isEditing.value = true;
  // 复制当前行数据
  currentTask.id = row.id;
  currentTask.resultName = row.resultName;
  currentTask.taskType = row.taskType;
  currentTask.taskSource = row.taskSource;
  currentTask.detectionTime = row.detectionTime;
  
  dialogVisible.value = true;
};

// 确认对话框（创建/编辑）
const confirmDialog = async (task: any) => {
  try {
    // 校验必填项
    if (!task.resultName || !task.taskType || !task.taskSource) {
      ElMessage.warning("请填写必要信息");
      return;
    }

    // 根据是否是编辑状态选择不同的接口
    const apiUrl = isEditing.value 
      ? "/algorithmApi/task-result/update" 
      : "/algorithmApi/task-result/create";

    // 发起请求
    const response = await axios.post(apiUrl, task);

    // 关闭弹窗
    dialogVisible.value = false;

    // 刷新列表
    ElMessage.success(isEditing.value ? "修改成功" : "创建成功");
    fetchTaskResults();
  } catch (error) {
    console.error(isEditing.value ? "修改任务失败:" : "创建任务失败:", error);
    ElMessage.error(isEditing.value ? "修改任务失败" : "创建任务失败");
  }
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该任务吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 发起删除请求
      await axios.post("/algorithmApi/task-result/delete", { id: row.id });
      
      // 提示并刷新列表
      ElMessage.success('删除成功');
      fetchTaskResults();
    } catch (error) {
      console.error("删除任务失败:", error);
      ElMessage.error("删除任务失败");
    }
  }).catch(() => {
    // 取消删除
    ElMessage.info('已取消删除');
  });
};

// 处理下载
const handleDownload = (row: any) => {
  console.log(`下载任务：${row.resultName}`);
};

// 应用筛选
const applyFilters = () => {
  // 重置到第一页
  currentPage.value = 1;
  // 重新获取数据
  fetchTaskResults();
};

// 重置筛选条件
const resetFilters = () => {
  filters.detectionTime = "";
  filters.resultName = "";
  filters.taskType = "";
  filters.taskSource = "";

  // 重置到第一页
  currentPage.value = 1;
  // 重新获取数据
  fetchTaskResults();
};

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchTaskResults();
};

// 页面挂载时获取初始数据
onMounted(() => {
  fetchTaskResults();
});
</script>

<style scoped>
.button-group {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.query-form {
  display: flex;
  flex-direction: column;
}

.query-form .el-form-item {
  margin-bottom: 15px;
}
</style>

<style lang="scss">
.task-card {
  background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
  box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
  border-radius: 3px;
  left: 34px;
  top: 120px;
  padding: 10px;
  overflow: scroll;
  overflow-x: hidden;

  .el-form-item {
    margin-bottom: 5px !important;
  }

  .el-select__wrapper,
  .el-input__wrapper {
    box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
  }

  .filter-container {
    .el-input__wrapper {
      background: rgba(34, 42, 51, 0.5);
      color: #d1e5ff;
    }
  }

  .el-table {
    --el-table-header-bg-color: #1b384d9c !important;
    --el-table-tr-bg-color: #2a57779c !important;
    --el-table-border-color: rgb(109, 194, 236);
    --el-table-row-hover-bg-color: #152b3a9c !important;

    tr {
      cursor: pointer;
      color: #ccc;
      background: none;
    }

    .el-table__body tr.current-row > td.el-table__cell {
      background-color: #0c1b2975;
      color: #fff;
    }
  }

  .page-container {
    --el-input-border-color: rgb(109, 194, 236) !important;

    .el-input__wrapper {
      box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
    }

    .el-select {
      --el-select-border-color-hover: rgb(109, 194, 236) !important;
    }
  }
}
.query-buttons {
  padding: 20px 20px 0;
  width: 100%;
}
</style>